<template>
  <el-dialog :title="mode === 'edit' ? '编辑规格' : '新建规格'" v-model="isShowDialog" :destroy-on-close="true"
    :close-on-click-modal="false" @closed="handleDialogClose" @opened="handleDialogOpened">
    <el-form ref="productFormRef" :model="productForm" :rules="productFormRules" :label-width="80" v-loading="loading">
      <el-form-item label="选择规格" v-if="mode !== 'edit'">
        <el-select v-model="selectedProductModel" @change="selectProduct" placeholder="请选择规格" clearable>
          <el-option v-for="(item) in productsOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <template v-if="selectedProductModel || mode === 'edit'">
        <el-form-item label="规格名称" prop="name">
          <el-input v-model.trim="productForm.name" placeholder="请输入规格名称" show-word-limit maxlength="15"></el-input>
        </el-form-item>
        <el-form-item label="规格图片" prop="thumbnailUrl">
          <upload v-model:model-value="productForm.thumbnailUrl" list-type="picture-card" :limit="1">
            <template #default>
              <el-icon>
                <plus />
              </el-icon>
            </template>
          </upload>
        </el-form-item>
        <el-form-item label="市场价格">
          {{ isNaN(productForm.originalPrice) ? productForm.originalPrice : productForm.originalPrice / 100 }} 元
        </el-form-item>
        <el-form-item label="售价" prop="combinedPrice">
          <div style="display: flex;flex-wrap: nowrap;">
            <el-input v-model="productForm.payOfCurrencyCount" type="number">
              <template #append>
                积分
              </template>
            </el-input>
            <div style="width: 10px"></div>
            <el-input v-model="productForm.payPrice" type="number">
              <template #append>
                元
              </template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label="总库存" prop="totalStock">{{ productForm.totalStock }}</el-form-item>
        <el-form-item label="商城库存" prop="stock">{{ productForm.stock }}</el-form-item>
        <el-form-item label="商家库存" prop="beforeStock">{{ productForm.beforeStock }}</el-form-item>
        <el-form-item label="库存增减" prop="addOrDeductionStockCount">
          <el-radio-group v-model="addOrDeductionSymbolModel">
            <el-radio-button label="+">增</el-radio-button>
            <el-radio-button label="-" v-if="mode === 'edit'">减</el-radio-button>
          </el-radio-group>
          <div style="width: 5px"></div>
          <el-input-number :step="1" step-strictly v-model="productForm.addOrDeductionStockCount"
            :min="mode === 'edit' ? 0 : 1"></el-input-number>
        </el-form-item>
      </template>
    </el-form>

    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="save">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { IStoreGoodsDetail, IStoreProductRow } from "@/api/modules/pointsMall";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { getStoreGoodsDetail, saveProduct } from "@/api/pointsMall";
import { useMallConfig } from "@/views/pointsMall/compositions/useMallConfig";

const props = defineProps<{
  mode: 'edit' | 'create',
  show: boolean,
  rowData: IStoreProductRow
}>()
const emits = defineEmits(['update:show', 'saved'])

const route = useRoute()
const { mallConfig } = useMallConfig()
const isShowDialog = computed({
  get() {
    return props.show
  },
  set(val) {
    emits("update:show", val)
  }
})

const productFormRef = ref<FormInstance>()
const productForm = reactive<IStoreProductRow>({} as any)
const productFormRules = ref<FormRules>({
  name: [{
    required: true,
    message: '请输入规格名称',
    trigger: 'blur'
  }],
  thumbnailUrl: [{
    required: true,
    message: '请上传规格图片',
    trigger: 'blur'
  }],
  combinedPrice: [{
    required: true,
    trigger: 'blur',
    validator(rule, val, callback) {
      if (!/^(0|[1-9][0-9]*)$/.test('' + productForm.payOfCurrencyCount)) {
        callback(new Error('售价（积分）只能为0或正整数'))
      } else if (Number(productForm.payOfCurrencyCount) > 9999999999) {
        callback(new Error('售价（积分），超过上限【99,9999,9999】'))
      } else if (!/(^[0-9]+$)|(^[0-9]+\.[0-9]{1,2}$)/.test('' + productForm.payPrice)) {
        callback(new Error('售价（现金）不正确，不能为负数且仅保留2位小数'))
      } else if (Number(productForm.payPrice) > 9999999999) {
        callback(new Error('售价（现金），超过上限【99,9999,9999】'))
      } else {
        callback()
      }
    }
  }],
  addOrDeductionStockCount: [{
    required: true,
    trigger: 'blur',
    validator(rule, val, callback) {
      const _addOrDeductionStockCount = Number(addOrDeductionSymbolModel.value + productForm.addOrDeductionStockCount ?? 0)
      console.log(_addOrDeductionStockCount)
      if (props.mode === 'edit') {
        if (!isEmpty(_addOrDeductionStockCount)) { // 填写了库存增减量
          if (_addOrDeductionStockCount > 0 && _addOrDeductionStockCount > productForm.beforeStock) {
            callback(new Error('库存【增】量不能大于商家库存'))
          } else if (_addOrDeductionStockCount < 0 && Math.abs(_addOrDeductionStockCount) > productForm.stock) {
            callback(new Error('库存【减】量不能大于商城库存'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      } else {
        if (isEmpty(_addOrDeductionStockCount)) {
          callback(new Error('【库存增减量】不能为空'))
        } else if (_addOrDeductionStockCount < 1) {
          callback(new Error('【库存增减量】不能小于1'))
        } else if (_addOrDeductionStockCount > productForm.beforeStock) {
          callback(new Error('库存【增】量不能大于商家库存'))
        } else {
          callback()
        }
      }
    }
  }]
})
const addOrDeductionSymbolModel = ref<'+' | '-'>('+')
// const validateAddOrDeductionStockCount = (rule, val, callback) => {
//   if (isEmpty(productForm.addOrDeductionStockCount)) {
//     callback(new Error('库存增减量不能为空'))
//   } else if (productForm.addOrDeductionStockCount < 1 && props.mode === 'create') {
//     callback(new Error('库存增减量不能小于1'))
//   } else if (Math.abs(productForm.addOrDeductionStockCount) > productForm.beforeStock && props.mode === 'edit') {
//     callback(new Error('库存增减量不能大于预占库存'))
//   } else {
//     callback()
//   }
// }

const selectedProductModel = ref<IStoreProductRow>()
// 选择后添加规格行
const selectProduct = (val: string) => {
  const target = productsOptions.value.find(item => item.id === val)
  if (target) {
    Object.keys(target).forEach(key => {
      productForm[key] = target[key]
    })
    productForm.mallId = mallConfig.value.id
    productForm.goodsId = route.query.id as string
    productForm.storeGoodsId = storeGoodsDetail.value?.id
    productForm.storeProductId = target.id
    productForm.id = null // 后端视id存在与否区别编辑和新增
    productForm.stock = 0
    productForm.totalStock = 0
    productForm.payOfCurrencyCount = 0
  }
}

const formatData = () => {
  const _productForm = { ...productForm }
  _productForm.payPrice = parseInt((_productForm.payPrice * 100).toFixed(2).slice(0, -3))
  // 后端以分为单位保存
  _productForm.addOrDeductionStockCount = Number(addOrDeductionSymbolModel.value + productForm.addOrDeductionStockCount ?? 0)
  return _productForm
}

const isEmpty = (val: any) => {
  return val === undefined || val === null || val === ''
}

const save = async (row: IStoreProductRow, index: number) => {
  productFormRef.value?.validate(async (valid, field) => {
    if (valid) {
      const _productForm = formatData()
      const rs = await saveProduct(_productForm)

      if (rs.code === 200) {
        ElMessage.success('保存成功')
        // _getSpecificationList()
        isShowDialog.value = false
        emits('saved')
      }
    } else {
      console.log(field)
    }
  })
}

const cancel = () => {
  isShowDialog.value = false
}

const storeGoodsDetail = ref<IStoreGoodsDetail>()
// 可选商品规格选项
const productsOptions = ref<IStoreProductRow[]>([])
// 获取商家的可选商品规格
const _getStoreGoodsDetail = async () => {
  const id = route.query.storeGoodsId as unknown as string
  const rs = await getStoreGoodsDetail({ id })

  if (rs.code === 200) {
    if (rs.payload) {
      storeGoodsDetail.value = rs.payload
      productsOptions.value = rs.payload.products.map(item => ({
        ...item,
        thumbnailUrl: item.thumbnailUrl ?? '', // upload组件需要
        addOrDeductionStockCount: 0, // 库存增减量
      }))
    }
  }
}

const echoExistsProduct = () => {
  Object.keys(props.rowData).forEach(key => {
    productForm[key] = props.rowData[key]
  })
  productForm.payPrice = productForm.payPrice / 100 // 后端以分为单位保存
  productForm.beforeStock = productsOptions.value.find(storeProduct => storeProduct.id === productForm.storeProductId)?.beforeStock ?? 0
  productForm.addOrDeductionStockCount = 0
}

const loading = ref(false)
const handleDialogOpened = async () => {
  loading.value = true
  await _getStoreGoodsDetail()
  if (props.mode === 'edit') {
    echoExistsProduct()
  }
  loading.value = false
}

const handleDialogClose = () => {
  selectedProductModel.value = undefined
  Object.keys(productForm).forEach(key => {
    productForm[key] = null
  })
}
</script>

<style scoped lang="scss"></style>
